package com.alan.netty.io;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.*;

/**
 * @author weiBin
 * @date 2018/11/5
 */
public class ThreadPoolServer {
    static int port = 8081;

    public static void main(String[] args) {
        try {
            System.out.println(String.format("服务端端口%s等待连接", port));
            ThreadPoolExecutor executor = new ThreadPoolExecutor(2, 3, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(1));
            ServerSocket serverSocket = new ServerSocket(port);
            int i = 0;
            while (true) {
                Socket socket = serverSocket.accept();
                executor.execute(new HandleRequestRunnable(socket, ++i));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

class HandleRequestRunnable implements Runnable {
    private Socket socket;
    private int clineNo;

    public HandleRequestRunnable(Socket socket, int clineNo) {
        this.clineNo = clineNo;
        this.socket = socket;
    }

    @Override
    public void run() {
        PrintWriter out = null;
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new PrintWriter(socket.getOutputStream(), true);
            String inputLine = null;
            while ((inputLine = reader.readLine()) != null) {
                System.out.println(String.format("客户端%s输入%s", clineNo, inputLine));
                out.println(String.format("服务器输出:%s", inputLine));
                if ("Quit".equals(inputLine)) {
                    out.close();
                    reader.close();
                    socket.close();
                    System.out.println(String.format("客户端%s退出了!", clineNo));
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }
    }
}
